Differences between Assert.True and Assert.IsTrue in NUnit? - nunit

Is there any differences between those two?

No difference. Assert.True() and others (without Is) were added since v2.5.
From documentation for the version 2.5: (nunit v2.5)
Two forms are provided for the True, False, Null and NotNull
conditions. The "Is" forms are compatible with earlier versions of the
NUnit framework, while those without "Is" are provided for
compatibility with NUnitLite
BTW, Disassembled nunit.framework.dll (using ILSPY)
public static void IsTrue(bool condition)
{
Assert.That(condition, Is.True, null, null);
}
public static void True(bool condition)
{
Assert.That(condition, Is.True, null, null);
}

There does not seem to be any implementational difference. Looking at the source code for the most recent version here, the True, IsTrue and That are all implemented in the same way when the argument lists are the same:
public static void True(bool condition, string message, params object[] args)
{
Assert.That(condition, Is.True, message, args);
}
...
public static void IsTrue(bool condition, string message, params object[] args)
{
Assert.That(condition, Is.True, message, args);
}
...
static public void That(bool condition, string message, params object[] args)
{
Assert.That(condition, Is.True, message, args);
}
The overloaded methods are implemented analogously.

Related

Why does the implementation functions report an error in drools 7.51.0.Final?

I use accumulate with inline custom code crrectly in drools 7.33.0.Final,but get a error() in 7.51.0.Final.
The error is "Legacy accumulate can be used only with drools-mvel on classpath".so I try to implement my own accumulate functions,but has another error(xxx cannot be cast to org.kie.api.runtime.rule.AccumulateFunction).even though I totally copy the example code ,the error also happened.
public class TotalAccumulateFunction implements org.kie.api.runtime.rule.AccumulateFunction<TotalAccumulateFunction.TotalData>{
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
}
public void writeExternal(ObjectOutput out) throws IOException {
}
public static class TotalData implements Externalizable {
public int total = 0;
public TotalData() {}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
total = in.readInt();
}
public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt(total);
}
}
public TotalData createContext() {
return new TotalData();
}
public void init(TotalData context) {
context.total = 0;
}
public void accumulate(TotalData context,
Object value) {
context.total += ((Number) value).doubleValue();
}
public void reverse(TotalData context, Object value) {
context.total -= ((Number) value).doubleValue();
}
public Object getResult(TotalData context) {
return context.total == 0 ? 0 : context.total;
}
public boolean supportsReverse() {
return true;
}
public Class< ? > getResultType() {
return Number.class;
}
}
Since Drools 7.45.0.Final drools-mvel has been moved to a separated module for better modularization.
See the release notes.
Drools engine usages of MVEL and ASM are isolated in a new
drools-mvel module. This new module is strictly required on the
classpath for all usages that do not involve the executable model.
Note that this is not related to the dialect in use. In the usual DRL
compilation, both Java and MVEL dialects rely on MVEL for parsing and
on ASM for bytecode generation. In both cases, it is a must to have
drools-mvel in your classpath.
If you plan to use the "classic" Drools with MVEL instead of the executable model, you might consider depending on the wrapper module drools-engine-classic
This issue is mainly caused by the fact that users have among their
dependencies modules like drools-core and drools-compiler that in
reality are no more than "internal implementation details". To avoid
similar problems in future, in the very likely case that other modules
will be introduced to split engine in finer grained submodules and
descope optional features, the following 2 new wrapper modules have
been created to cover the 2 different main usage scenarios:
drools-engine aggregating drools-core, drools-compiler and
drools-model-compiler
drools-engine-classic aggregating drools-core, drools-compiler and
drools-mvel

Difference between SendAsync and SendCoreAsync methods in SignalR Core?

When updating to the latest version of ASP Net Core and SignalR core, I noticed there are two "send" methods available when sending methods to a client (what used to be InvokeAsync).
After looking at the code comments, both methods are identical in comments, both inherit from IClientProxy, and both accept a string method, object args and then a cancellation token.
What are the differences in these methods? If any? and which should be used when?
Quoting #anurse from GitHub:
Long story short:
The Core methods should be ignored unless you really know what you're doing.
Short story long:
We started with SendAsync, which takes an array of arguments to send:
public void SendAsync(string method, object[] args);
Clients.All.SendAsync("Method", new object[] { arg1, arg2, arg3 });
Obviously it's a pain to have to create an array every time. The easy
fix for that would be to use params:
public void SendAsync(string method, params object[] args);
Clients.All.SendAsync("Method", arg1, arg2, arg3);
However, that falls apart when you actually want to send an array as a
single argument
public void SendAsync(string method, params object[] args);
var arg1 = new object[] { a, b, c };
Clients.All.SendAsync("Method", arg1);
// C# 'params' expands this into the below
Clients.All.SendAsync("Method", a, b, c);
So instead of sending a single argument that is an array a, b, c,
we've sent each of those as separate arguments. This was confusing
users.
So we removed the params from it and instead we generate a whole bunch
of extension methods that support multiple arguments:
public void SendAsync(string method, object[] args);
public void SendAsync(string method, object arg1) => SendAsync(method, new object[] { arg1 });
public void SendAsync(string method, object arg1, object arg2) => SendAsync(method, new object[] { arg1, arg2 });
// ... etc ...
But there's still ambiguity when you have code like this:
public void SendAsync(string method, object[] args);
public void SendAsync(string method, object arg1) => SendAsync(method, new object[] { arg1 });
var arg = new object[] { a, b, c }
Clients.All.SendAsync("method", arg);
Again, the overload that takes an object[] will be chosen (see this
illustration on SharpLab).
So, we renamed the one that takes an array to SendCoreAsync:
public void SendCoreAsync(string method, object[] args);
public void SendAsync(string method, object arg1) => SendCoreAsync(method, new object[] { arg1 });
var arg = new object[] { a, b, c }
// No ambiguity here!
Clients.All.SendAsync("method", arg);

No error message from Validator in spring-data-rest

Following the documentation http://docs.spring.io/spring-data/rest/docs/2.4.2.RELEASE/reference/html/#validation I set up a very simple Validator for a spring-data-rest repository invocation:
public class DealValidator implements Validator {
#Override
public boolean supports(Class<?> aClass) {
return Deal.class.isAssignableFrom(aClass);
}
#Override
public void validate(Object o, Errors errors) {
errors.reject("deal.error", "No deal");
}
}
And this is the configuration
#Override
protected void configureValidatingRepositoryEventListener(ValidatingRepositoryEventListener validatingListener) {
validatingListener.addValidator("beforeCreate", new DealValidator());
}
#Configuration
static class I18nConfiguration {
#Bean
public ResourceBundleMessageSource messageSource() {
ResourceBundleMessageSource source = new ResourceBundleMessageSource();
source.setBasename("classpath:messages");
return source;
}
}
The configuration seems to be alright, the validator is called correctly, the http-request yields an error response, but no error text is returned, neither from the messages.properties nor the default text. Is this a bug?
I came across the same issue. Only validation errors that reference a field are serialized by spring-data-rest.
So you could use rejectValue(String field, String errorCode, String defaultMessage) instead of reject
See org.springframework.data.rest.webmvc.support.RepositoryConstraintViolationExceptionMessage for implementation details. The implementation just processes org.springframework.validation.Errors#getFieldErrors().

How to get plugins by setting a path

I created console c# project. and in the code I have made a module. My code looks like this.
[Import]
public IMessageSender MessageSender { get; set; }
public static void Main(string[] args)
{
Program p = new Program();
p.Run();
}
public void Run()
{
Compose();
Console.ReadLine(MessageSender.Send("Message Sent"));
}
private void Compose()
{
AssemblyCatalog catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
var container = new CompositionContainer(catalog);
container.ComposeParts(this);
}
public interface IMessageSender
{
string Send(string message);
}
[Export(typeof(IMessageSender))]
public class EmailSender : IMessageSender
{
public void Send(string message)
{
return message;
}
}
It works perfectly fine. But now I added a new project in my solution and added module into that
AnotherProject->EmailSender.cs
[Export(typeof(IMessageSender))]
public class EmailSender : IMessageSender
{
public void Send(string message)
{
return message;
}
}
Now in the main console program I changed some of my code.
private void Compose()
{
var catalog = new DirectoryCatalog(path);
//AssemblyCatalog catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
var container = new CompositionContainer(catalog);
container.ComposeParts(this);
}
But now when I run this program. It doesnt load the module. MessageSender in main program is null. What wrong I have done.
There are a few things you need to check:
Have you correctly referenced the assemblies?
The DirectoryCatalog by default uses the search pattern *.dll. Because you have a console application, which uses the .exe extension, no exports in that assembly will get picked up by the DirectoryCatalog - with the default search pattern. You'll likely want to use an AggregateCatalog, passing in the DirectoryCatalog (*.dll), and either another DirectoryCatalog (*.exe), or an AssemblyCatalog, of the entry assembly.
You currently have one [Import] where you may end up with multiple [Export(typeof(IMessageSender))], you didn't state that you have moved the EmailSender to the class library, merely that you have created a new one, which means you'll likely end up with a cardinality mismatch where it is expecting a sinple import, you have many exports. This will explicitly throw an exception, which is what will happen even it couldn't find a single instance of IMessageSender, because your [Import] attribute is not set to allow a default value where no part can be provided. If you need to be fault tollerant, you can use [Import(AllowDefault = true)]
Incidentally... the above code won't compile, I assume it was just an example and not a copy-paste from your current code?
public void SendMessage(string message)
{
return message;
}
You're retuning a message to a void method - that can't be done, and it also means that EmailSender doesn't correctly implement IMessageSender. Not too bothered, as I think it is an example more than actual code.

Using structuremap with log4net wrapper

I have the following interface:
public interface ILogger
{
void Debug(string message, params object[] values);
void Info(string message, params object[] values);
void Warn(string message, params object[] values);
void Error(string message, params object[] values);
void Fatal(string message, params object[] values);
}
and the following implementation:
public class Log4netLogger : ILogger
{
private ILog _log;
public Log4netLogger(Type type)
{
_log = LogManager.GetLogger(type);
}
public void Debug(string message, params object[] values)
{
_log.DebugFormat(message, values);
}
// other logging methods here...
}
My idea was to use structuremap to instantiate the Log4netLogger class with using the Type of the class that did the logging. However, I can't for the life of me figure out how to pass the type of the calling class to structuremap so that it can be passed to the constructor of the logging implementation. Any advice on how to do that (or a better way) would be most appreciated.
We use a similar ILogger wrapper around log4net and typically use constructor injection. We use an interceptor as a factory method responsible for creating the Logger. Here is our typical registry for logging setup.
public class CommonsRegistry : Registry
{
public CommonsRegistry()
{
For<ILogger>()
.AlwaysUnique()
.TheDefault.Is.ConstructedBy(s =>
{
if (s.ParentType == null)
return new Log4NetLogger(s.BuildStack.Current.ConcreteType);
return new Log4NetLogger(s.ParentType);
});
var applicationPath = Path.GetDirectoryName(Assembly.GetAssembly(GetType()).Location);
var configFile = new FileInfo(Path.Combine(applicationPath, "log4net.config"));
XmlConfigurator.ConfigureAndWatch(configFile);
}
}
The parent type null check is necessary when there are dependencies on concrete types.
The rest is optional log4net setup stuff.
One thing I do like about this setup is the ability to use a null loggers for unit testing.
If the type parameter is context-specific, I don't think this is going to work as shown. If you need to pass something context specific in the constructor, you are likely going to have to create a factory interface and implementation that returns an instance of the ILogger:
public interface ILoggerFactory
{
ILogger Create(Type type);
}
public class LoggerFactory : ILoggerFactory
{
public ILogger Create(Type type)
{
return new Log4netLogger(type);
}
}
It might be possible to bootstrap StructureMap to supply the instance you want based on the type, but that assumes a limited number of types that you know in advance.
I really need to get out of the habit of answering my own question, but for those who run across it, here's the answer.
return ObjectFactory.With(type).GetInstance<T>();
I actually have a wrapper to structuremap (to avoid exposing the structuremap dependency to my app) that looks like the following:
public static class ServiceManager
{
public static T Get<T>()
{
return ObjectFactory.GetInstance<T>();
}
public static T Get<T>(Type type)
{
return ObjectFactory.With(type).GetInstance<T>();
}
}
Any time in the code I need a logger, I call the following:
ServiceManager.Get<ILogger>(GetType()).Info("Logging page view...");