I've created a class that is used as ClassData to a Xunit test method marked with Theory attribute.
I am getting a following error message
I was checking other StackOverflow answers regarding this but I am not sure what could possibly wrong.
I am sure that I am wrapping new [,] {...} and 1 within new object[]{...}, which is what should be returned to the ClassData attribute.
Would someone point out what I am doing wrong here?
Could it possibly a bug in ReSharper Xunit test runner (R# version used is 2016.2)?
Test Class
public class Chapter1_8Test : BaseTest
{
private readonly Chapter1_8 _sut = new Chapter1_8();
public Chapter1_8Test(ITestOutputHelper output) : base(output)
{
}
[Theory]
[ClassData(typeof(Chapter1_8Data))]
public void TestGettingZeroPositions(int[,] matrix, int expected)
{
_output.WriteLine(matrix.ToString());
}
}
Class Data
public class Chapter1_8Data : IEnumerable<object[]>
{
private readonly List<object[]> _data = new List<object[]>
{
new object[]
{
new[,] { { 0, 1, 2 }, { 3, 4, 5 } },
1
}
};
public IEnumerator<object[]> GetEnumerator()
{
return _data.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
Related
Update 1
Following the suggestion by Lucian, I removed the attributes from the classes used for the property and added a profile; like this, both tests succeed:
public class TargetBaseClass
{
}
public class TargetConcreteClass : TargetBaseClass
{
}
public class TestProfile : Profile
{
public TestProfile()
{
this.CreateMap<TargetBaseClass, SourceBaseClass>()
.Include<TargetConcreteClass, SourceConcreteClass>();
this.CreateMap<TargetConcreteClass, SourceConcreteClass>();
this.CreateMap<SourceBaseClass, TargetBaseClass>()
.Include<SourceConcreteClass, TargetConcreteClass>();
this.CreateMap<SourceConcreteClass, TargetConcreteClass>();
}
}
The question is: can it be translated to AutoMap attribute(s)?
I have several derived classes and I will might add more in the future.
The attribute looked at first sight an easy way to do it.
original question
I'm having issues using AutoMapper with the AutoMapAttribute.
I created the following test:
namespace Tests
{
using AutoMapper;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
public class SourceContainerClass
{
public SourceBaseClass MyProperty { get; set; }
}
public class SourceBaseClass
{ }
public class SourceConcreteClass : SourceBaseClass
{ }
[AutoMap(typeof(SourceContainerClass), ReverseMap = true)]
public class TargetContainerClass
{
public TargetBaseClass MyProperty { get; set; }
}
[AutoMap(typeof(SourceBaseClass), ReverseMap = true, IncludeAllDerived = true)]
public class TargetBaseClass
{ }
[AutoMap(typeof(SourceConcreteClass), ReverseMap = true)]
public class TargetConcreteClass : TargetBaseClass
{ }
public class AutoMapperTests
{
[Fact]
public void TestSourceToTargetMapping()
{
var services = new ServiceCollection().AddAutoMapper(this.GetType().Assembly).BuildServiceProvider();
var mapper = services.GetRequiredService<IMapper>();
var source = new SourceContainerClass
{
MyProperty = new SourceConcreteClass()
};
var target = mapper.Map<TargetContainerClass>(source);
Assert.IsType<TargetConcreteClass>(target.MyProperty);
}
[Fact]
public void TestBackwardMapping()
{
var services = new ServiceCollection().AddAutoMapper(this.GetType().Assembly).BuildServiceProvider();
var mapper = services.GetRequiredService<IMapper>();
var source = new TargetContainerClass
{
MyProperty = new TargetConcreteClass()
};
var back = mapper.Map<SourceContainerClass>(source);
Assert.IsType<SourceConcreteClass>(back.MyProperty);
}
}
}
With the second test failing:
Tests.AutoMapperTests.TestBackwardMapping:
Outcome: Failed
Error Message:
Assert.IsType() Failure
Expected: Tests.SourceConcreteClass
Actual: Tests.SourceBaseClass
Stack Trace:
at Tests.AutoMapperTests.TestBackwardMapping() in /{..}/AutoMapperTests.cs:line 59
Tests.AutoMapperTests.TestSourceToTargetMapping:
Outcome: Passed
Total tests: 2. Passed: 1. Failed: 1. Skipped: 0
Is this mapping not supported or am I missing something?
I'm referencing the package AutoMapper.Extensions.Microsoft.DependencyInjection 7.0.0.
I am trying to get multiple mocks working in groovy. The only way I have managed to get this working is to create my own kind of mock - adding a meta method.
I have tried using nested use statements and also tried one use and one proxy with verify, neither of which worked. Both of these returned a failure - "junit.framework.AssertionFailedError: No more calls to 'pop' expected at this point. End of demands."
import groovy.mock.interceptor.MockFor
import org.junit.Test
class MockTest {
// results in No more calls to 'pop' expected at this point. End of demands.
#Test
public void testMock() {
MockFor pupilMock = new MockFor(Pupil)
MockFor bubbleMock = new MockFor(SomeService)
GroovyObject bubbleProxy = bubbleMock.proxyInstance()
pupilMock.demand.blowBubble { String colour ->
return bubbleProxy
}
bubbleMock.demand.pop {}
pupilMock.use {
bubbleMock.use {
Teacher teacher = new Teacher()
teacher.lesson("red")
}
}
}
// results in No more calls to 'pop' expected at this point. End of demands.
#Test
public void testProxy() {
MockFor pupilMock = new MockFor(Pupil)
MockFor bubbleMock = new MockFor(SomeService)
GroovyObject bubbleProxy = bubbleMock.proxyInstance()
pupilMock.demand.blowBubble { String colour ->
return bubbleProxy
}
bubbleMock.demand.pop {}
pupilMock.use {
Teacher teacher = new Teacher()
teacher.lesson("red")
}
bubbleMock.verify(bubbleProxy)
}
// only using a single mock so works
#Test
public void testMetaclass() {
MockFor pupilMock = new MockFor(Pupil)
SomeService.metaClass.pop = { println "pop was called" }
SomeService metaBubble = new SomeService("red")
pupilMock.demand.blowBubble { String colour ->
return metaBubble
}
pupilMock.use {
Teacher teacher = new Teacher()
teacher.lesson("red")
}
}
}
class Teacher {
public void lesson(String colour) {
Pupil pupil = new Pupil()
SomeService bubble = pupil.blowBubble(colour)
bubble.pop()
}
}
class Pupil {
SomeService blowBubble(String colour) {
SomeService child = new SomeService(colour)
return child
}
}
class SomeService {
String colour
SomeService(String colour) {
this.colour = colour
}
void pop() {
println "popped ${colour}"
}
}
EDIT: Re comment about mocking something constructed and returned from a method, this is how I do it...
#Test
public void testMockReturned() {
MockFor bubbleMock = new MockFor(SomeService)
bubbleMock.demand.pop {}
bubbleMock.use {
Pupil pupil = new Pupil()
SomeService service = pupil.blowBubble("red")
service.pop()
}
}
In this case, Pupil should be a stub since you're only using it to inject bubbleProxy to you can perform verification against it. Like this,
import groovy.mock.interceptor.*
import org.junit.Test
class MockTest {
#Test
public void testMock() {
StubFor pupilMock = new StubFor(Pupil)
MockFor bubbleMock = new MockFor(SomeService)
GroovyObject bubbleProxy = bubbleMock.proxyInstance()
pupilMock.demand.blowBubble { String colour ->
return bubbleProxy
}
bubbleMock.demand.pop {}
bubbleMock.use {
Teacher teacher = new Teacher()
teacher.lesson("red")
}
}
}
Also, I believe the demands are copied onto the proxy when proxyInstance() is called, so you need to have your demands configured before instantiating the proxy.
However, I don't think there's a problem with multiple mocks, I think you just can't mix instance and class mocks (which you are doing with SomeService). The smallest example I could think of that demonstrates this was
import groovy.mock.interceptor.MockFor
// this works
missyMock = new MockFor(Missy)
missyMock.demand.saySomethingNice {}
missy = missyMock.proxyInstance()
missy.saySomethingNice()
missyMock.verify(missy)
// as does this
missyMock = new MockFor(Missy)
missyMock.demand.saySomethingNice {}
missyMock.use {
new Missy().saySomethingNice()
}
// this don't
missyMock = new MockFor(Missy)
missyMock.demand.saySomethingNice {}
missy = missyMock.proxyInstance()
missyMock.use { // fails here in use()'s built-in verify()
missy.saySomethingNice()
}
missyMock.verify(missy)
class Missy {
void saySomethingNice() {}
}
To demonstrate that the multiple mocks with nested use closures works, look at this contrived example
import groovy.mock.interceptor.MockFor
import org.junit.Test
class MockTest {
#Test
public void testMock() {
MockFor lessonMock = new MockFor(Lesson)
MockFor pupilMock = new MockFor(Pupil)
lessonMock.demand.getLessonPlan {}
pupilMock.demand.getName {}
pupilMock.use {
lessonMock.use {
Teacher teacher = new Teacher()
Pupil pupil = new Pupil()
Lesson lesson = new Lesson()
teacher.teach(pupil, lesson)
}
}
}
}
class Teacher {
void teach(Pupil pupil, Lesson lesson) {
println "Taught ${pupil.getName()} $lesson by ${lesson.getLessonPlan()}"
}
}
class Pupil {
String name
}
class Lesson {
LessonPlan lessonPlan
static class LessonPlan {}
}
Im trying to write simple things with Apache Wicket (6.15.0) and Groovy (2.2.2 or 2.3.1). And Im having trouble with inner classes.
class CreatePaymentPanel extends Panel {
public CreatePaymentPanel(String id) {
super(id)
add(new PaymentSelectFragment('currentPanel').setOutputMarkupId(true))
}
public class PaymentSelectFragment extends Fragment {
public PaymentSelectFragment(String id) {
super(id, 'selectFragment', CreatePaymentPanel.this) // problem here
add(new AjaxLink('cardButton') {
#Override
void onClick(AjaxRequestTarget target) {
... CreatePaymentPanel.this // not accessible here
}
})
add(new AjaxLink('terminalButton') {
#Override
void onClick(AjaxRequestTarget target) {
... CreatePaymentPanel.this // not accessible here
}
});
}
} // end of PaymentSelectFragment class
} // end of CreatePaymentPanel class
Groovy tries to find a property "this" in CreatePaymentPanel class.. How to workaround this? It is a valid java code, but not groovy.
However,
Test.groovy:
class Test {
static void main(String[] args) {
def a = new A()
}
static class A {
A() {
def c = new C()
}
public void sayA() { println 'saying A' }
class B {
public B(A instance) {
A.this.sayA()
instance.sayA()
}
}
/**
* The problem occurs here
*/
class C extends B {
public C() {
super(A.this) // groovy tries to find property "this" in A class
sayA()
}
}
}
}
Above code wont work, the same error occurs, like in Wicket's case.
And TestJava.java, the same and working:
public class TestJava {
public static void main(String[] args) {
A a = new A();
}
static class A {
A() {
C c = new C();
}
public void sayA() {
System.out.println("saying A");
}
class B {
public B(A instance) {
instance.sayA();
}
}
/**
* This works fine
*/
class C extends B {
public C() {
super(A.this);
sayA();
}
}
}
}
What I am missing?
You can't refer to a CreatePaymentPanel.this inside of PaymentSelectFragment because there is no instance of CreatePamentPanel that would be accessible there. What would you expect that to evaluate to if it were allowed?
I am trying to learn IOC principle from this screencast
Inversion of Control from First Principles - Top Gear Style
I tried do as per screencast but i get an error while AutomaticFactory try create an object of AutoCue. AutoCue class has contructor which takes IClock and not SystemClock. But my question is , in screencast IClock is resolved with SystemClock while inside AutomaticFactory .But in my code , IClock does not get resolved . Am i missing something ?
class Program
{
static void Main(string[] args)
{
//var clarkson = new Clarkson(new AutoCue(new SystemClock()), new Megaphone());
//var clarkson = ClarksonFactory.SpawnOne();
var clarkson = (Clarkson)AutomaticFactory.GetOne(typeof(Clarkson));
clarkson.SaySomething();
Console.Read();
}
}
public class AutomaticFactory
{
public static object GetOne(Type type)
{
var constructor = type.GetConstructors().Single();
var parameters = constructor.GetParameters();
if (!parameters.Any()) return Activator.CreateInstance(type);
var args = new List<object>();
foreach(var parameter in parameters)
{
var arg = GetOne(parameter.ParameterType);
args.Add(arg);
}
var result = Activator.CreateInstance(type, args.ToArray());
return result;
}
}
public class Clarkson
{
private readonly AutoCue _autocue;
private readonly Megaphone _megaphone;
public Clarkson(AutoCue autocue,Megaphone megaphone)
{
_autocue = autocue;
_megaphone =megaphone;
}
public void SaySomething()
{
var message = _autocue.GetCue();
_megaphone.Shout(message);
}
}
public class Megaphone
{
public void Shout(string message)
{
Console.WriteLine(message);
}
}
public interface IClock
{
DateTime Now { get; }
}
public class SystemClock : IClock
{
public DateTime Now { get { return DateTime.Now; } }
}
public class AutoCue
{
private readonly IClock _clock;
public AutoCue(IClock clock)
{
_clock = clock;
}
public string GetCue()
{
DateTime now = _clock.Now;
if (now.DayOfWeek == DayOfWeek.Sunday)
{
return "Its a sunday!";
}
else
{
return "I have to work!";
}
}
}
What you basically implemented is a small IoC container that is able to auto-wire object graphs. But your implementation is only able to create object graphs of concrete objects. This makes your code violate the Dependency Inversion Principle.
What's missing from the implementation is some sort of Register method that tells your AutomaticFactory that when confronted with an abstraction, it should resolve the registered implementation. That could look as follows:
private static readonly Dictionary<Type, Type> registrations =
new Dictionary<Type, Type>();
public static void Register<TService, TImplementation>()
where TImplementation : class, TService
where TService : class
{
registrations.Add(typeof(TService), typeof(TImplementation));
}
No you will have to do an adjustment to the GetOne method as well. You can add the following code at the start of the GetOne method:
if (registrations.ContainsKey(type))
{
type = registrations[type];
}
That will ensure that if the supplied type is registered in the AutomaticFactory as TService, the mapped TImplementation will be used and the factory will continue using this implementation as the type to build up.
This does mean however that you now have to explicitly register the mapping between IClock and SystemClock (which is a quite natural thing to do if you're working with an IoC container). You must make this mapping before the first instance is resolved from the AutomaticFactory. So you should add the following line to to the beginning of the Main method:
AutomaticFactory.Register<IClock, SystemClock>();
I have this class as parent class:
public partial class GetStuffResult
{
private int _Id;
private string _Name;
public GetStuffResult()
{
}
[Column(Storage="_Id", DbType="INT NOT NULL")]
public int Id
{
get
{
return this._Id;
}
set
{
if ((this._Id != value))
{
this._Id = value;
}
}
}
[Column(Storage="_Name", DbType="NVarChar(100)")]
public string Name
{
get
{
return this._Name;
}
set
{
if ((this._Name != value))
{
this._Name = value;
}
}
}
}
This is base class which has same methods with exception of an extra method:
public partial class GetStuffResult1
{
private int _Score;
private int _Id;
private string _Name;
public GetStuffResult1()
{
}
[Column(Storage="_Score", DbType="INT NOT NULL")]
public int Id
{
get
{
return this._Score;
}
set
{
if ((this._Score != value))
{
this._Score = value;
}
}
}
[Column(Storage="_Id", DbType="INT NOT NULL")]
public int Id
{
get
{
return this._Id;
}
set
{
if ((this._Id != value))
{
this._Id = value;
}
}
}
[Column(Storage="_Name", DbType="NVarChar(100)")]
public string Name
{
get
{
return this._Name;
}
set
{
if ((this._Name != value))
{
this._Name = value;
}
}
}
}
I have done inheritance before but i am totally confused how it will work in this scenario? How can i inherit GetStuffResult so that i can use its 2 methods and dont have to copy paste same code twice in GetStuffResult1.
Will appreciate if someone can give example with code as i am new to .net 3.5 and still trying to learn it.
I am not sure if I correctly understood your question. (Your current code for GetStuffResult1 shouldn't compile as you have define Id property twice.) If you are looking to inherit from GetStuffResult then this would do (See Inheritance):
public partial class GetStuffResult1 : GetStuffResult
{
private int _Score;
public GetStuffResult1()
{
}
[Column(Storage = "_Score", DbType = "INT NOT NULL")]
public int Id
{
get
{
return this._Score;
}
set
{
if ((this._Score != value))
{
this._Score = value;
}
}
}
}
Notice that I have removed _Id and _Name from the child class. This however will give you warning that:
GetStuffResult1.Id' hides inherited member
'ThreadConsoleApp.GetStuffResult.Id'. Use the new keyword if hiding
was intended.
The second thing I am thinking about your question if you are confused about using partial classes and you may need a single class in multiple source file. In that case you may use partial keyword. If that is the case and you don't need inheritance then you need to use a single name for the class. e.g. GetStuffResult. In that particular case your GetStuffResult1 will become:
public partial class GetStuffResult
{
private int _Score;
public GetStuffResult1()
{
}
[Column(Storage = "_Score", DbType = "INT NOT NULL")]
public int Id
{
get
{
return this._Score;
}
set
{
if ((this._Score != value))
{
this._Score = value;
}
}
}
}
This will be similar to having a single class with all the combined properties.
Edit:
To access the base class properties in the child class, you may use base keyword.
base.Id = 0;
base.Name = "SomeName";
To access the base class properties from the object of GetStuffResult1, see the following example.
GetStuffResult1 gsr1 = new GetStuffResult1();
gsr1.Id = 0;
gsr1.Name = "SomeName";
Here gsr1.Name is from the base class, you may use different name for Id in either base or child class so that it can be more clearer.